import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../../common/utils/enums.dart';
import 'light_control_bottom_item.dart';

typedef LightControlBottomTapCallback = void Function(int index);

class LightControlBottom extends StatefulWidget {
  const LightControlBottom(
      {super.key, required this.currectIndex, this.tapCallback,required this.type});
  final int currectIndex;
  final LightControlBottomTapCallback? tapCallback;
  final DeviceLListType type;

  @override
  State<LightControlBottom> createState() {
    return _LightControlBottomState();
  }
}

class _LightControlBottomState extends State<LightControlBottom> {
  final ScrollController _scrollController = ScrollController();

  @override
  void didUpdateWidget(covariant LightControlBottom oldWidget) {
    if (widget.currectIndex != oldWidget.currectIndex) {
      int key = widget.currectIndex - 2;
      if (key < 0) {
        return;
      }

      if (GlobalObjectKey(key).currentContext != null) {
        RenderObject? keyRenderObject = GlobalObjectKey(key)
            .currentContext
            ?.findAncestorRenderObjectOfType();
        _scrollController.position.ensureVisible(keyRenderObject!,
            duration: const Duration(milliseconds: 300), curve: Curves.easeIn);
      }
    }

    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: 134.h,
        decoration: const BoxDecoration(color: Color(0xff323232), boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(0, 0, 0, 0.15),
            offset: Offset(0, -4),
            blurRadius: 25,
          )
        ]),
        child: _buildBottomGridView());
  }

  // 底部控制区域
  Widget _buildBottomGridView() {
    return GridView.builder(
        controller: _scrollController,
        padding: const EdgeInsets.fromLTRB(12, 10, 12, 34).r,
        scrollDirection: Axis.horizontal,
        itemCount: 8,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1, // 主轴上Item长度
          mainAxisSpacing: 12.r, // 主轴item之间的间距
          childAspectRatio: 6 / 9.0, //宽高比
          mainAxisExtent: 60.r,
        ),
        itemBuilder: _buildBottomGridViewItem);
  }

  // 底部控制区域item
  Widget _buildBottomGridViewItem(BuildContext context, int index) {
    return LightControlBottomitem(
      key: GlobalObjectKey(index),
      type: widget.type,
      selected: widget.currectIndex == index ? true : false,
      roomName: widget.type==DeviceLListType.light?'客厅':'书房',
      deviceName: widget.type==DeviceLListType.light?'阅读灯':'空调',
      index: index,
      tapCallback: () {
        widget.tapCallback!(index);
      },
    );
  }
}
